package com.ocm.tourism.picasaweb.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.springframework.stereotype.Service;

@Service("googleAuthentication")
public class GoogleAuthenticationServiceImpl implements GoogleAuthenticationService {

   private String keyAuthentication;

   public String getAuthenticationString(){
      if (keyAuthentication == null)
         keyAuthentication = processAuthenticationString();
      return keyAuthentication;
   }

   private String processAuthenticationString() {
      String auth = null;
      try {
         String email = "dulichtayninh2@gmail.com";
         String password = "passw)rd@123";

         // check if user set email and password in preferences
         if (email.trim().length() == 0 || password.trim().length() == 0) {
            return null;
         }

         // url to authenticate on
         String authUrl = "https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email=" + email + "&Passwd="
               + password + "&service=lh2&source=PicasaUploader";

         // create ssl context
         SSLContext sc = SSLContext.getInstance("TLS");

         // override ssl context with our own class, otherwise ssl will fail
         sc.init(null, new TrustManager[] { new MyTrustManager() }, new SecureRandom());

         // create url connection
         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
         HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
         HttpsURLConnection con = (HttpsURLConnection) new URL(authUrl).openConnection();

         // set timeout and that we do output
         con.setReadTimeout(15000);
         con.setDoOutput(true);
         con.connect();

         // read response from url and accumulate body
         BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
         StringBuffer sb = new StringBuffer();
         String line;

         while ((line = br.readLine()) != null) {
            sb.append(line);
         }

         // create body and check if it containts auth string
         String body = sb.toString();
         Integer index = body.indexOf("Auth=");

         // if body contains auth string save it
         if (index != -1) {
            auth = body.substring(index + 5);
         }
      } catch (Exception e) {
      }

      // return auth for further use in the application
      return auth;
   }

   /**
    * Override class so SSL will work
    */
   private class MyHostnameVerifier implements HostnameVerifier {
      @Override
      public boolean verify(String hostname, SSLSession session) {
         return true;
      }
   }

   /**
    * Override class so SSL will work
    */
   private class MyTrustManager implements X509TrustManager {
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType) {
      }

      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType) {
      }

      @Override
      public X509Certificate[] getAcceptedIssuers() {
         return null;
      }
   }
}
